import java.util.LinkedList;
import java.util.Queue;

public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
 }

class Solution {
    //解法1：DFS深度优先搜索 一般使用递归或栈实现
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int leftTree = maxDepth(root.left);
        int rightTree = maxDepth(root.right);
        return leftTree > rightTree ? leftTree + 1 : rightTree + 1;
        //简洁写法
        //return root == null ? 0 : Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
    //解法2：BFS广度优先搜索 一般使用队列实现
    public int maxDepth2(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        int count = 0;
        queue.offer(root);
        while (!queue.isEmpty()) {
            count++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return count;
    }
}